<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="分类名称" prop="menuName">
        <el-input v-model="queryParams.menuName" placeholder="请输入商品分类名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini"
          v-hasPermi="['goods:category:add']" @click="handleAdd()">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini"
          @click="handleAllCategoryGoodsSkuImport" v-hasPermi="['goods:goods:sku:category:import']">
          导入分类商品</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-if="refreshTable" v-loading="loading" :data="categoryList" row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="name" label="分类名称" :show-overflow-tooltip="true" width="200">
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="120"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:category:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
            v-hasPermi="['goods:category:add']">新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['goods:category:remove']">删除</el-button>
          <el-button v-if="scope.row.level === 0 ? false : true" type="info" plain
            icon="el-icon-upload2" size="mini" @click="handleImport(scope.row)"
            v-hasPermi="['goods:goods:sku:import']">导入商品
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框  -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级分类">
              <treeselect v-model="form.parentId" :options="categoryOptions"
                :normalizer="normalizer" :show-count="true" placeholder="选择上级分类" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="分类层级" prop="level">
              <el-input-number v-model="form.level" controls-position="right" :min="0"  :max="1"/>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="显示排序" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品分类导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&categoryPath=' + categoryPath"
        :disabled=" upload.isUploading" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false"
            style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 所有商品分类导入对话框 -->
    <el-dialog :title="uploadAllCategoryGoodsSku.title"
      :visible.sync="uploadAllCategoryGoodsSku.open" width="400px" append-to-body>
      <el-upload ref="uploadAllCategoryGoodsSku" :limit="1" accept=".xlsx, .xls"
        :headers="uploadAllCategoryGoodsSku.headers"
        :action="uploadAllCategoryGoodsSku.url + '?updateSupport=' + uploadAllCategoryGoodsSku.updateSupport"
        :disabled="uploadAllCategoryGoodsSku.isUploading"
        :on-progress="handleAllCategoryGoodsSkuFileUploadProgress"
        :on-success="handleAllCategoryGoodsSkuFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="uploadAllCategoryGoodsSku.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false"
            style="font-size:12px;vertical-align: baseline;"
            @click="importAllCategoryGoodsSkuTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllCategoryGoodsSkuFileForm">确 定</el-button>
        <el-button @click="uploadAllCategoryGoodsSku.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCategory, addClassification, modifyClassification, deleteClassification } from "@/api/goods/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import { getToken } from "@/utils/auth";

export default {
  name: "Category",
  dicts: ['sys_show_hide', 'sys_normal_disable'],
  components: { Treeselect, IconSelect },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      categoryList: [],
      // 菜单树选项
      categoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        menuName: undefined,
        visible: undefined
      },
      // 表单参数
      form: {},
      // 分类商品导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 商品分类上传的地址
        url: process.env.VUE_APP_BASE_API + "/goods/goods/importData"
      },
      // 分类商品导入参数
      uploadAllCategoryGoodsSku: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 所有分类商品上传的地址
        url: process.env.VUE_APP_BASE_API + "/goods/goods/importData/all"
      },
      categoryPath: '',
    };
  },
  created () {
    this.getList();
  },
  methods: {
    // 选择图标
    selected (name) {
      this.form.icon = name;
    },
    /** 查询菜单列表 */
    getList () {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = this.handleTree(response.data, "id");
        this.loading = false;
      });
    },
    dateFormat (data, format) {
      let Y = data.getFullYear();
      let M = (data.getMonth() + 1).toString().padStart(2, 0);
      let D = (data.getDate()).toString().padStart(2, 0);
      let h = (data.getHours()).toString().padStart(2, 0);
      let m = (data.getMinutes()).toString().padStart(2, 0);
      let s = (data.getSeconds()).toString().padStart(2, 0);
      return format.replace("YYYY", Y).replace("MM", M).replace("DD", D).replace("hh", h).replace("mm", m).replace("ss", s);
    },
    /** 转换分类数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询商品分类下拉树结构 */
    getTreeselect () {
      listCategory().then(response => {
        this.categoryOptions = [];
        const category = { id: 0, name: '主分类', children: [] };
        category.children = this.handleTree(response.data);
        this.categoryOptions.push(category);
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,
        parentId: 0,
        name: undefined,
        icon: undefined,
        sortOrder: 0,
        isCache: "0",
        level: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.form.sortOrder = 0;
      this.open = true;
      this.title = "添加商品分类";
    },
    /** 展开/折叠操作 */
    toggleExpandAll () {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.open = true
      this.form = row
      this.title = "修改商品分类";
      this.getTreeselect();
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            modifyClassification(this.form.id, this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClassification(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(function () {
        return deleteClassification(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导入按钮操作 */
    handleImport (row) {
      this.upload.title = "商品分类导入";
      this.upload.open = true;
      this.categoryPath = row.parentId + ',' + row.id
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download('goods/goods/goods/importTemplate', {
      }, `商品分类模板_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}{i}{s}")}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    },
    /** 导入所有商品分类按钮操作 */
    handleAllCategoryGoodsSkuImport () {
      this.uploadAllCategoryGoodsSku.title = "所有商品分类导入";
      this.uploadAllCategoryGoodsSku.open = true;
    },
    /** 下载导入所有商品分类模板操作 */
    importAllCategoryGoodsSkuTemplate () {
      this.download('goods/goods/goods/importTemplate/all', {
      }, `所有商品分类模板_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}{i}{s}")}.xlsx`)
    },
    // 文件上传中处理
    handleAllCategoryGoodsSkuFileUploadProgress (event, file, fileList) {
      this.uploadAllCategoryGoodsSku.isUploading = true;
    },
    // 文件上传成功处理
    handleAllCategoryGoodsSkuFileSuccess (response, file, fileList) {
      this.uploadAllCategoryGoodsSku.open = false;
      this.uploadAllCategoryGoodsSku.isUploading = false;
      this.$refs.uploadAllCategoryGoodsSku.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitAllCategoryGoodsSkuFileForm () {
      this.$refs.uploadAllCategoryGoodsSku.submit();
    },
  }
};
</script>
